import tkinter as tk
from tkinter import messagebox, simpledialog
import os
import re

# 读取用户信息
def load_users():
    if not os.path.exists('users.txt'):
        return {}
    with open('users.txt', 'r') as file:
        lines = file.readlines()
    users = {}
    for line in lines:
        username, password = line.strip().split(':')
        users[username] = password
    return users

# 验证登录
def validate_login():
    username = entry_username.get()
    password = entry_password.get()
    users = load_users()
    
    if username in users and users[username] == password:
        messagebox.showinfo("成功", "登录成功")
        root.destroy()  # 关闭登录窗口
        student_management_page()  # 跳转到学生信息管理页面
    else:
        messagebox.showerror("错误", "用户名或密码错误")

# 登录界面
def login_page():
    global entry_username, entry_password, root
    root = tk.Tk()
    root.title("登录")
    root.geometry("300x200")

    label_username = tk.Label(root, text="用户名:")
    label_username.pack(pady=5)
    entry_username = tk.Entry(root)
    entry_username.pack(pady=5)

    label_password = tk.Label(root, text="密码:")
    label_password.pack(pady=5)
    entry_password = tk.Entry(root, show="*")
    entry_password.pack(pady=5)

    button_login = tk.Button(root, text="登录", command=validate_login)
    button_login.pack(pady=10)

    root.mainloop()

# 学生信息管理页面
def student_management_page():
    student_root = tk.Tk()
    student_root.title("学生信息管理")
    student_root.geometry("400x300")

    label_welcome = tk.Label(student_root, text="欢迎使用学生信息管理系统")
    label_welcome.pack(pady=20)

    button_add = tk.Button(student_root, text="添加学生信息", command=add_student)
    button_add.pack(pady=5)

    button_delete = tk.Button(student_root, text="删除学生信息", command=delete_student)
    button_delete.pack(pady=5)

    button_update = tk.Button(student_root, text="修改学生信息", command=update_student)
    button_update.pack(pady=5)

    button_query = tk.Button(student_root, text="查询学生信息", command=query_student)
    button_query.pack(pady=5)

    button_sort = tk.Button(student_root, text="排序学生信息", command=sort_students)
    button_sort.pack(pady=5)

    student_root.mainloop()

# 从文件中加载学生信息
def load_students():
    if not os.path.exists('students.txt'):
        return [["学号", "姓名", "性别", "年龄", "专业", "班级"]]
    with open('students.txt', 'r') as file:
        lines = file.readlines()
    students = []
    for line in lines:
        students.append(line.strip().split(','))
    return students

# 将学生信息保存到文件
def save_students(students):
    with open('students.txt', 'w') as file:
        for student in students:
            file.write(','.join(student) + '\n')

# 添加学生信息
def add_student():
    student_id = simpledialog.askstring("输入", "请输入学号:")
    if student_id is None:
        return
    name = simpledialog.askstring("输入", "请输入姓名:")
    if name is None:
        return
    gender = simpledialog.askstring("输入", "请输入性别:")
    if gender is None:
        return
    age = simpledialog.askinteger("输入", "请输入年龄:")
    if age is None:
        return
    major = simpledialog.askstring("输入", "请输入专业:")
    if major is None:
        return
    class_name = simpledialog.askstring("输入", "请输入班级:")
    if class_name is None:
        return
    new_student = [student_id, name, gender, str(age), major, class_name]
    students = load_students()
    students.append(new_student)
    save_students(students)
    messagebox.showinfo("成功", "学生信息添加成功")

# 删除学生信息
def delete_student():
    student_id = simpledialog.askstring("输入", "请输入要删除的学号:")
    if student_id is None:
        return
    students = load_students()
    found = False
    for student in students[1:]:
        if student[0] == student_id:
            students.remove(student)
            found = True
            break
    if found:
        save_students(students)
        messagebox.showinfo("成功", "学生信息删除成功")
    else:
        messagebox.showerror("错误", "未找到该学号的学生信息")

# 修改学生信息
def update_student():
    student_id = simpledialog.askstring("输入", "请输入要修改的学号:")
    if student_id is None:
        return
    students = load_students()
    found = False
    for student in students[1:]:
        if student[0] == student_id:
            found = True
            name = simpledialog.askstring("输入", "请输入新的姓名:", initialvalue=student[1])
            if name is None:
                return
            gender = simpledialog.askstring("输入", "请输入新的性别:", initialvalue=student[2])
            if gender is None:
                return
            age = simpledialog.askinteger("输入", "请输入新的年龄:", initialvalue=int(student[3]))
            if age is None:
                return
            major = simpledialog.askstring("输入", "请输入新的专业:", initialvalue=student[4])
            if major is None:
                return
            class_name = simpledialog.askstring("输入", "请输入新的班级:", initialvalue=student[5])
            if class_name is None:
                return
            student[1] = name
            student[2] = gender
            student[3] = str(age)
            student[4] = major
            student[5] = class_name
            break
    if found:
        save_students(students)
        messagebox.showinfo("成功", "学生信息修改成功")
    else:
        messagebox.showerror("错误", "未找到该学号的学生信息")

# 查询学生信息
def query_student():
    query_type = simpledialog.askstring("输入", "请输入查询类型 (学号/姓名):")
    if query_type is None:
        return
    query_value = simpledialog.askstring("输入", f"请输入{query_type}:")
    if query_value is None:
        return
    students = load_students()
    found = False
    result = []
    for student in students[1:]:
        if (query_type == "学号" and student[0] == query_value) or (query_type == "姓名" and student[1] == query_value):
            found = True
            result.append(student)
    if found:
        result_text = "\n".join([", ".join(student) for student in result])
        messagebox.showinfo("查询结果", result_text)
    else:
        messagebox.showerror("错误", f"未找到{query_type}为 {query_value} 的学生信息")

# 排序学生信息
def sort_students():
    sort_by = simpledialog.askstring("输入", "请输入排序字段 (学号/姓名/年龄):")
    if sort_by is None:
        return
    students = load_students()
    if sort_by == "学号":
        students[1:] = sorted(students[1:], key=lambda x: x[0])
    elif sort_by == "姓名":
        students[1:] = sorted(students[1:], key=lambda x: x[1])
    elif sort_by == "年龄":
        students[1:] = sorted(students[1:], key=lambda x: int(x[3]))
    else:
        messagebox.showerror("错误", "无效的排序字段")
        return
    save_students(students)
    messagebox.showinfo("成功", "学生信息排序成功")

if __name__ == "__main__":
    login_page()